package insat.ia.main;

import java.io.ObjectInputStream.GetField;
import java.util.ArrayList;

public class InferenceEngine_Avant extends InferenceEngine {

    public InferenceEngine_Avant(Dataengine dataengine, String but) {
        this.dataengine = dataengine;
        But = but;
    }

    public void chainageAvant() {

        Premisse but = new Premisse();
        but.add(this.But);

        ArrayList<Fait> bf = this.dataengine.getBFobjects();
        ArrayList<Regle> br = this.dataengine.getBRobjects();

   //     System.out.println("resultat existe ?   " + match(but, bf));
        ArrayList<Regle> tmp = getReglesDeclenchableSet();

        while (!(match(but, bf)) && (tmp.size() != 0)) {
//			System.out.println(" ---------nb regles declenchables : "
//					+ tmp.size());

            Regle regleChoisie = conflictResolution(tmp);

            for (int i = 0; i < tmp.size(); i++) {
                nbReglesAppliquee++;
                appliqueRegle(tmp.get(i));
            }
            // appliqueRegle(regleChoisie);
            dataengine.showData();

            if (!(match(but, bf)) && (tmp.size() != 0)) {
                tmp = getReglesDeclenchableSet();
            }
        }

        if (match(but, bf)) {
            butAttient = true;
        }

    }

    @Override
    public ArrayList<String> appliqueRegle(Regle r) {

        // applique la regle
        System.out.println("Application de la regle "+ r);
        if (!this.dataengine.withBFobjects(r.getConclusion())) {
            this.dataengine.BFobjects.add(new Fait(r.getNumero(), r
                    .getConclusion()));
        }
        // desactiver la regle
        this.dataengine.getBRobjects().remove(r);
        return new ArrayList<String>();
    }

    /*
     * retourne l'ensemble de regles declenchables
     */
    public ArrayList<Regle> getReglesDeclenchableSet() {

        ArrayList<Regle> result = new ArrayList<Regle>();

        for (int i = 0; i < dataengine.getBRobjects().size(); i++) {
//            System.out.println("test de la regle "
//                    + dataengine.BRobjects.get(i).getNumero());

            if (match(dataengine.BRobjects.get(i).getPremisse(),
                    dataengine.getBFobjects())) {
                result.add(dataengine.BRobjects.get(i));
            }

        }
        return result;

    }

}
